// pages/driving/driving.ts

// 初始化经纬度
import {durationStr, formatFee} from '../../utils/format'
import {routing} from '../../constant/routing.constant'
import {TripService} from '../../service/trip'

const initLongitude = 100.87264654736123
const initLatitude = 29.761267625855936
const img = '/resources/car.png'

Page({

    /**
     * 页面的初始数据
     */
    timer: undefined as number | undefined,
    data: {
        elapsed: '00:00:00',
        fee: '0.00',
        location: {
            longitude: initLongitude,
            latitude: initLatitude,
        },
        scale: 12,
        markers: [{
            iconPath: img,
            id: 0,
            // 经度
            longitude: initLongitude,
            // 纬度
            latitude: initLatitude,
            width: 20,
            height: 20
        }]
    },
    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(opt: Record<'trip_id', string>) {
        // 设置当前定位经纬度
        this.setCurrentLocation()

        // TODO
        let iTrip = await TripService.GetTrip(opt.trip_id)

        console.log(iTrip)

        // 计时器读秒
        this.setCurrentTimer(opt.trip_id)

    },
    async onUnload() {

        await wx.stopLocationUpdate()
        if (this.timer) {
            clearInterval(this.timer)
        }

    },
    /**
     * 设置当前定位经纬度
     */
    setCurrentLocation() {

        // 接收位置消息（前台)
        wx.startLocationUpdate({
            fail: console.error
        })

        // 监听实时地理位置变化事件
        wx.onLocationChange(location => {
            // console.log('location', location)
            this.setData({
                longitude: location.longitude,
                latitude: location.latitude
            })
        })
    },
    /**
     * 计时器读秒
     */
    setCurrentTimer(tripID: string) {
        console.log(tripID)
        let elapsedSec = 0
        let cents = 0
        this.timer = setInterval(() => {
            elapsedSec++
            cents += 0.7
            this.setData({
                elapsed: durationStr(elapsedSec),
                fee: formatFee(cents)
            })
        }, 1000)

    },
    /**
     * 结束行程
     */
    async onEndTripTap() {
        await wx.redirectTo({
            url: routing.mytrips()
        })
    }
})
